<template>
  <ele-page flex-table>
    <!-- 搜索表单 -->
    <PageSearch :supplierList @search="reload" />

    <ele-card :body-style="{ paddingTop: '8px' }">
      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        v-model:selections="selections"
        row-key="id"
        :columns="columns"
        :datasource="datasource"
        :show-overflow-tooltip="false"
        highlight-current-row
        cache-key="OutboundNoticeTable"
      >
        <template #toolbar>
          <!-- <el-button type="primary" @click="openPageTab('/open/transfer/edit/0')">新建</el-button> -->
        </template>

        <template #order_sn="{ row }">
          <ele-copyable :text="row.order_sn">
            <el-link type="primary" underline="never" @click="openPageTab(`/open/transfer/info/${row.id}`)">{{ row.order_sn }}</el-link>
          </ele-copyable>
        </template>

        <template #third_party_sn="{ row }">
          <ele-copyable v-if="row.third_party_sn" :text="row.third_party_sn">
            {{ row.third_party_sn }}
          </ele-copyable>
        </template>

        <template #status="{ row }">
          <el-tag :type="getType(row.status)">{{ row.status_name }}</el-tag>
        </template>
        <template #enter_status="{ row }">
          <el-tag :type="getType(row.enter_status)">{{ row.enter_status_name }}</el-tag>
        </template>
        <template #delivery_status="{ row }">
          <el-tag :type="getType(row.delivery_status)">{{ row.delivery_status_name }}</el-tag>
        </template>

        <template #action="{ row }">
          <div class="flex-ea">
            <template v-if="row.acts.length">
              <ele-dropdown
                :items="row.acts"
                @command="value => onCommand(value, row)"
              >
                <el-button
                  type="primary"
                  link
                >
                  <el-icon :size="16" class="block ml-4px"><IconElEditPen /></el-icon>
                </el-button>
              </ele-dropdown>
              <el-divider direction="vertical" />
            </template>

            <el-link type="primary" underline="never" @click="onCommand('INFO', row)">
              <ele-dot v-if="row.acts.length" type="danger" ripple text="详情" />
              <span v-else>详情</span>
            </el-link>
          </div>
        </template>
      </ele-pro-table>
    </ele-card>

    <PageReview
      v-model="showReview"
      remarkDisabled
      :statusList="[
        {
          value: 'SL',
          label: '受理',
        },
        {
          value: 'JJ',
          label: '拒绝',
        },
      ]"
      @done="review"
    />
  </ele-page>
</template>

<script setup>
import { listSupplier } from '@/api/common'
import PageReview from '@/components/Common/Review.vue'
import { ref } from 'vue'

import PageSearch from './components/search.vue'

defineOptions({ name: 'OpenTransfer' })

const showReview = ref(false)

const current = ref(null)

const router = useRouter()

const { addPageTab } = utils.usePageTab()

const { getType } = utils

/** 表格实例 */
const tableRef = ref(null)

const [supplierList] = utils.useGetList(listSupplier)

/** 表格选中数据 */
const selections = ref([])

// 激活页面刷新table
utils.useActivatedReload(() => tableRef.value?.reload?.())

/** 表格列配置 */
const columns = ref([
  {
    type: 'selection',
    columnKey: 'selection',
    width: 40,
    align: 'center',
    fixed: 'left',
    showOverflowTooltip: false,
  },
  {
    type: 'index',
    label: '序',
    width: 50,
    align: 'left',
    fixed: 'left',
  },
  {
    prop: 'order_sn',
    label: '单据编号',
    width: 200,
    align: 'left',
    slot: 'order_sn',
  },
  {
    prop: 'third_party_sn',
    label: '第三方单号',
    width: 180,
    align: 'left',
    slot: 'third_party_sn',
  },
  {
    prop: 'order_date',
    label: '单据日期',
    minWidth: 100,
    align: 'center',
  },
  {
    prop: 'supplier_name',
    label: '货主',
    minWidth: 110,
    align: 'center',
  },
  {
    prop: 'su_name',
    label: '对外平台',
    minWidth: 110,
    align: 'center',
  },
  {
    prop: 'status_name',
    slot: 'status',
    label: '订单状态',
    align: 'center',
    width: 100,
  },
  {
    prop: 'enter_status_name',
    slot: 'enter_status',
    label: '收货状态',
    align: 'center',
    width: 100,
  },
  {
    prop: 'delivery_status_name',
    slot: 'delivery_status',
    label: '发货状态',
    align: 'center',
    width: 100,
  },
  {
    prop: 'product_num',
    label: '品数',
    align: 'center',
    width: 100,
  },
  {
    prop: 'num',
    label: '调拨数量',
    align: 'center',
    width: 100,
  },
  {
    prop: 'enter_num',
    label: '收货数量',
    align: 'center',
    width: 100,
  },
  {
    prop: 'remark',
    showOverflowTooltip: true,
    label: '备注',
    align: 'center',
    width: 110,
  },
  {
    prop: 'create_time',
    label: '创建时间',
    formatter: (row) => {
      return utils.formatDate(row.create_time)
    },
    align: 'center',
    width: 160,
    showOverflowTooltip: false,
  },
  {
    columnKey: 'action',
    label: '操作',
    align: 'right',
    slot: 'action',
    fixed: 'right',
    showOverflowTooltip: false,
    width: 110,
  },
])

function openPageTab(path) {
  addPageTab({
    key: path,
    closable: true,
  })
  router.push(path)
}

/** 表格数据源 */
async function datasource({ page, limit, where, orders }) {
  const res = await utils.get('/apiTransfer/index', { ...where, ...orders, page, limit })
  res.data.forEach((v) => {
    v.acts = getActs(v, true)
  })
  return res
}

/** 搜索 */
function reload(where) {
  selections.value = []
  tableRef.value?.reload?.({ page: 1, where })
}

function updateStatus(url, formData, cb) {
  const loading = utils.message('请求中..', 'loading')
  utils.post(url, formData).then((res) => {
    utils.message(res.msg, res.success)
    if (res.success) {
      reload()
      showReview.value = false
    }
  }).finally(() => {
    cb && cb()
    loading.close()
  })
}

function review(data, cb) {
  const id = current.value?.id ? [current.value.id] : selections.value.map(v => v.id)
  updateStatus('/apiTransfer/review', {
    status: data.status,
    id,
  }, cb)
}

function onCommand(command, row) {
  current.value = row?.id ? row : null
  const id = row?.id ? row.id : selections.value[0].id
  // const ids = row?.id ? [row.id] : selections.value.map(v => v.id)

  if (['INFO', 'EDIT'].includes(command)) {
    const _row = current.value ?? selections.value[0]

    const path = `/open/transfer/${command.toLowerCase()}/${_row.id}`

    openPageTab(path)
  }
  else if (command === 'SH') {
    showReview.value = true
  }
  else {
    // PH 配货， FS 反审， OK 已结单
    const list = [
      { key: 'CD', title: '取消' },
      { key: 'PH', title: '配货' },
      { key: 'FS', title: '反审' },
      { key: 'OK', title: '结单' },
    ]
    const item = list.find(v => v.key === command)
    const otps = {
      type: 'warning',
      dangerouslyUseHTMLString: true,
    }
    if (command === 'CD') {
      otps.ancelButtonText = '不取消了'
      otps.confirmButtonText = '确定取消'
    }
    utils.confirm(`确定要<span class="px-2px text-danger font-semibold">${item.title}</span>订单吗`, '系统提示', otps).then(() => {
      updateStatus('/apiTransfer/review', { id, status: command })
    })
  }
}

function getActs(row, filter = false) {
  const list = [
    { title: '编辑', command: 'EDIT', disabled: row.is_edit !== 1, icon: 'IconElEdit' },
    { title: '审核', command: 'SH', disabled: row.is_sl !== 1, icon: 'IconElStamp' },
    { title: '反审', command: 'FS', disabled: row.is_fs !== 1, icon: 'IconElStamp' },
    { title: '配货', command: 'PH', disabled: row.is_ph !== 1, icon: 'IconElStamp' },
    { title: '结单', command: 'OK', disabled: row.is_ok !== 1, icon: 'IconElCheck' },
    { title: '取消', command: 'CD', disabled: row.is_cd !== 1, icon: 'IconElClose' },
  ]
  if (filter) {
    return list.filter(v => !v.disabled)
  }
  return list
}
</script>
